<!--  -->
<template>
  <div class="choiceness flex column">
    <div class="chatBox flex column grow" ref="chatBox" @scroll="tumble">
      <div class="chat-items-wrap flex column grow" ref="chatWrap">
        <div class="noMore flex column grow" v-if="messageList.length < 1">
          <p>暂无数据</p>
        </div>
        <div
          class="chat-item clear"
          :class="{ user: item.puiblisherid == userId }"
          v-for="(item, index) in messageList"
          :key="index"
        >
          <div class="time">{{ item._publishTime }}</div>
          <div class="line1 clear">
            <span class="photo">
              <img :src="item.teacherPhoto || item.userPhoto" alt />
            </span>
            <span class="name">{{ item.teacherName || item.userName }}</span>
            <span class="cerName" v-if="item.cerName">
              证书编号{{ item.cerName }}
            </span>
            <i v-if="item.user_type == 1" class="user_type"> </i>
            <i v-if="item.user_type == 1" class="user_type jx"> </i>
          </div>

          <div class="line2 clear">
            <div class="content" v-html="item.content" @click="viewImg"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="box flex column">
      <span class="toDown" @click="putDown" v-show="shrink.switch">
        {{ shrink.text }}
      </span>
    </div>
    <openImg v-bind:imgSrc.sync="imgSrc"></openImg>
  </div>
</template>

<script>
import { getStockList, getFineList } from "../api/index";
import * as fn from "../script/utils";
import debounce from "lodash/debounce";
import { Toast } from "vant";
import format from "date-fns/format";
// import getUrlParams from "../../common/common";
import { getUrlParams } from "../script/utils";

const { token, productId, userId } = getUrlParams();
import { mapState } from "vuex";
import openImg from "../component/openImg";
// const token =
//   "CN,4G3Btpq682wh2Nq1di9qPHIDI69y64uZYs7LHKFg6m9t.lI6NWPlWLBIVmBY2itTEhk9adNLQmSzrFQeG1h0sZsRK3xp,7O.z.vBD5BktwRMDAuUjWi0oiNzgJMBbs1ikkTlrXmqWf6Xuucm8z5rkWSLzI1GP36jg0F.,zPR7k66sJxlrM0Spef1j4sUEMqfzQ917lcI_";
// const productId = 80;
// const userId = 1121;
import behavior from "../script/behavior";
const userData = { ...behavior };
function handler(arr) {
  return arr.map((item) => {
    item.code = item.stockCode.replace(/[^\d]+/, "");
    return item;
  });
}

export default {
  data() {
    return {
      stockList: [],
      messageList: [],
      userId: userId,
      // sinceId: "",
      size: 0, //记录当前加载条数
      content: "",
      count: 150,
      listShow: false,
      // version: version,
      stock: "",
      imgSrc: "",
      shrink: {
        switch: false,
        aggregate: 0,
        text: "回到底部",
      },
      // numQuestions: "", //已提问次数
    };
  },

  components: { openImg },

  computed: { ...mapState(["choicenessMessage"]) },
  watch: {
    choicenessMessage(data) {
      this.size = 0;
      this.getFineList();
      // this.putDown();
    },
    stock: debounce(async function () {
      if (this.stock.length >= 1) {
        // const { stocks } =
        await getStockList({ content: this.stock }).then((back) => {
          if (back.status == 1) {
            let stocks = back.data.stocks;
            if (stocks.length > 0) {
              this.stockList = handler(stocks);
              this.listShow = true;
            }
          }
        });
      } else {
        this.listShow = false;
      }
    }, 500),
    content: debounce(function () {
      if (this.content.length > 150) {
        this.content = this.content.substr(0, 150);
        return;
      }
      this.count = 150 - this.content.length;
      let day = localStorage.getItem("day");
    }, 500),
  },
  mounted() {
    this.getFineList();
    this.$nextTick(() => {
      // this.putDown();
      document.body.addEventListener("click", (e) => {
        if (e.target.className === "_stockCode") {
          var type = e.target.getAttribute("data-market");
          var code = e.target.getAttribute("data-code");
          this.link(type, code);
        }
      });
    });
  },

  methods: {
    tumble: debounce(function (e) {
      const { path } = e;
      if (
        path[0].scrollTop + path[0].clientHeight <
        path[0].scrollHeight - 10
      ) {
        this.shrink.switch = true;
      } else {
        this.shrink.switch = false;
        this.shrink.aggregate = 0;
        this.shrink.text = "回到底部";
      }
      if (path[0].scrollTop < 20) {
        this.getFineList();
      }
    }, 300),
    //跳转个股详情
    link(type, code) {
      type = type == "SS" ? "1" : "0";
      window.prompt(
        "",
        `up://["open.stock",${Date.now()},{"setcode":"${type}","code":"${code}","type":"首页"}]`
      );
    },
    reset() {
      this.listShow = false;
      this.stock = "";
      this.stockList = [];
    },

    //精选列表
    async getFineList() {
      await getFineList({
        clientCentralToken: token,
        pageSize: this.size,
      }).then((back) => {
        if (back.status == 1) {
          let data = back.data;
          console.log(data.length);
          if (data.length < 1) return;
          if (this.size == 0) {
            this.messageList = data.map((item) => {
              item.content = fn.higihLighttStock(item.content);
              item._publishTime = fn.timeFormat(
                item.pubtime,
                "yyyy-MM-dd HH:mm"
              );
              return item;
            });
            setTimeout(() => {
              this.putDown();
            }, 100);
          } else {
            const box = this.$refs.chatBox;
            const boxed = box.scrollHeight; //记住上一次的滚动位置
            console.log(data);
            this.messageList = data
              .map((item) => {
                item.content = fn.higihLighttStock(item.content);
                item._publishTime = fn.timeFormat(
                  item.pubtime,
                  "yyyy-MM-dd HH:mm"
                );
                return item;
              })
              .concat(this.messageList);

            //数据加载更多后定位滚动位置
            this.$nextTick(() => {
              box.scrollTop = box.scrollHeight - boxed;
            });
          }
          this.size = this.messageList.length;
        }
      });
    },
    viewImg(e) {
      if (e.path[0].tagName == "IMG") {
        this.imgSrc = e.path[0].src;
      }
    },

    //置底
    putDown() {
      const box = this.$refs.chatBox;
      this.shrink.aggregate = 0;
      this.shrink.text = "回到底部";
      console.log("t", box.scrollTop, "h", box.scrollHeight);
      this.$nextTick(() => {
        box.scrollTop = box.scrollHeight;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.choiceness {
  // width: 689px;
  height: 100%;
  border-radius: 8px;
  border: 1px solid rgba(69, 72, 85, 0.8);
  background: rgba(13, 18, 30, 0.8);
  // background: #fff;
}
.title {
  height: 52px;
  align-items: center;
  color: #e1e1e1;
  font-weight: 400;
  background: #262831;
  padding-left: 13px;
  border-radius: 8px 8px 0 0;
  .bhead {
    display: inline-block;
    width: 124px;
    height: 40px;
    line-height: 40px;
    font-size: 18px;
    padding-left: 50px;
    box-sizing: border-box;
    margin-right: 10px;
    color: #fec587;
    &.icon {
      background: url($PIC_URL + "/tlbypcWeb/extremeLive/zzds_icon.png")
        no-repeat left center;
    }
  }

  .titleTxt {
    letter-spacing: 1px;
    font-size: 16px;
    color: #bcbfc4;
    // width: 73%;
    // margin-right: 40px;
  }
}
.chat-items-wrap {
  width: 90%;
}
.noMore {
  padding-top: 100px;
  text-align: center;
  font-size: 18px;
  color: #fff;
}
.toDown {
  background-image: url($PIC_URL + "/tlbypcWeb/extremeLive/db_icon.png");
  background-repeat: no-repeat;
  background-position: right 10px center;
}
.box {
  position: relative;
}
.toDown {
  position: absolute;
  right: 0;
  top: -36px;
  display: inline-block;
  background-color: #2a427e;
  background-image: url($PIC_URL + "/tlbypcWeb/extremeLive/db_icon.png");

  cursor: pointer;
  line-height: 26px;
  font-size: 12px;
  font-weight: 400;
  color: #fff;
  border-radius: 4px 0px 0px 4px;
  padding: 0 26px 0 10px;
}
.user_type {
  position: relative;
  top: -7px;
  display: inline-block;
  margin-left: 6px;
  width: 35px;
  height: 16px;
  background: url($PIC_URL + "/tlbypcWeb/extremeLive/zhubo.png") no-repeat;
  background-size: 100%;
  &.jx {
    background: url($PIC_URL + "/tlbypcWeb/extremeLive/jingxuan.png") no-repeat;
  }
}
</style>
